package org.example.day11;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.11.2 hasWaiters(Condition condition):
 *      判断某锁下某个condition下等待的线程的个数
 *      注意:线程被唤醒时，直接退出等待队列，即使没有获取到CPU执行权
 **/
public class MyThread11 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition newCondition = lock.newCondition();
    public void waitMethod(){
        try {
            lock.lock();
            newCondition.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("③等待Condition的线程数是: " +lock.getWaitQueueLength(newCondition)); //9
            lock.unlock();
        }
    }
    public void notifyMethod(){
        try {
            lock.lock();
            System.out.println("是否有线程正在等待Condition? " + lock.hasWaiters(newCondition));
            System.out.println("①等待Condition的线程数是: " +lock.getWaitQueueLength(newCondition)); //10
            newCondition.signal();
            System.out.println("②等待Condition的线程数是: " +lock.getWaitQueueLength(newCondition)); //9
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread11 m11 = new MyThread11();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                m11.waitMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }
        Thread.sleep(2000);
        m11.notifyMethod();
    }
}
